//! Other statement parsing (export, defer)

use super::super::{parse_expression, Parser};
use crate::ast::stmt::{DeferStmt, ExportItem, ExportStmt};
use crate::error::{CompilerError, Result};
use crate::lexer::token::Token;

/// Parse export statement
pub fn parse_export_statement(parser: &mut Parser) -> Result<ExportStmt> {
    parser.expect(&Token::Export)?;

    let mut items = Vec::new();

    // Parse export items
    if parser.consume(&Token::LeftBrace)? {
        // Named exports: { add, PI }
        loop {
            if let Some(Token::Identifier(name)) = parser.peek().map(|t| &t.token) {
                let name = name.clone();
                parser.advance()?;
                items.push(ExportItem::Function(name));

                if parser.consume(&Token::Comma)? {
                    continue;
                } else {
                    break;
                }
            } else {
                break;
            }
        }
        parser.expect(&Token::RightBrace)?;
    } else if let Some(Token::Identifier(name)) = parser.peek().map(|t| &t.token) {
        // Single export: export fn add
        let name = name.clone();
        parser.advance()?;
        items.push(ExportItem::Function(name));
    } else {
        return Err(CompilerError::syntax(
            parser.current_location().line,
            parser.current_location().column,
            "Expected export items",
        ));
    }

    Ok(ExportStmt {
        items,
        location: parser.current_location(),
    })
}

/// Parse defer statement
pub fn parse_defer_statement(parser: &mut Parser) -> Result<DeferStmt> {
    parser.expect(&Token::Defer)?;

    let expr = parse_expression(parser)?;
    if expr.is_none() {
        return Err(CompilerError::syntax(
            parser.current_location().line,
            parser.current_location().column,
            "Expected expression after 'defer'",
        ));
    }

    // 可选的分号，支持无分号语法
    parser.consume(&Token::Semicolon)?;

    Ok(DeferStmt {
        expr: expr.unwrap(),
        location: parser.current_location(),
    })
}
